package com.converse.diamondreader.activities.findId;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Pair;
import android.view.OrientationEventListener;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.mlkit.vision.text.Text;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import androidx.annotation.NonNull;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.core.content.ContextCompat;

/**
 * Author: Administrator
 * Date: 2021/12/7
 * Project: DiamondReader
 * Description:
 */
public class FindIdPresenter {

    private FindIdView mView;
    private FindIdModel mModel;
    private ListenableFuture<ProcessCameraProvider> mFuture;
    private ProcessCameraProvider mCameraProvider;
    private Preview mPreview;

    public FindIdPresenter(FindIdView view, FindIdModel model) {
        this.mView = view;
        this.mModel = model;
    }

    public void displayVersion() {
        try {
            PackageInfo packageInfo = mView.getContext().getPackageManager().getPackageInfo(mView.getContext().getPackageName(), 0);
            String version = packageInfo.versionName;
            mView.showVersionCode(version);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void startPreview() {
        mFuture = ProcessCameraProvider.getInstance(mView.getContext());
        mFuture.addListener(new Runnable() {
            @Override
            public void run() {
                try {
                    mCameraProvider = mFuture.get();
                    DisplayMetrics metrics = mView.getContext().getResources().getDisplayMetrics();
                    Log.e("xxx", "metrics with="+metrics.widthPixels+" metrics height="+metrics.heightPixels);
                    ImageAnalysis imageAnalysis = mModel.buildImageAnalysisObj(metrics.widthPixels,metrics.heightPixels);
                    imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(mView.getContext()), new ImageAnalysis.Analyzer() {
                        @Override
                        public void analyze(@NonNull ImageProxy image) {
                            Task<Text> task = handleProcessImage(image);
                            if (task != null) {
                                task.addOnCompleteListener(new OnCompleteListener<Text>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Text> task) {
                                        image.close();
                                    }
                                });
                            }
                        }
                    });

                    CameraSelector selector = mModel.buildCameraSelectorObj();

                    mPreview = mModel.buildPreviewObj(metrics.widthPixels,metrics.heightPixels);
                    mPreview.setSurfaceProvider(mView.getViewFinder().getSurfaceProvider());
                    mPreview.setTargetRotation(mView.getWindowDisplay().getRotation());

                    mCameraProvider.unbindAll();
                    mCameraProvider.bindToLifecycle(mView.getLifeCycleOwner(),selector,mPreview, imageAnalysis);
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, ContextCompat.getMainExecutor(mView.getContext()));

    }

    private Task<Text> handleProcessImage(ImageProxy image) {
        return mModel.processTextRecognition(image, new OnSuccessListener<Text>() {
            @Override
            public void onSuccess(@NonNull Text text) {
                handleResultText(text);
            }
        }, new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                mView.showToast(e.getMessage());
            }
        });
    }

    private void handleResultText(Text text) {
        List<Text.Line> lines = new ArrayList<>();
        for (Text.TextBlock block : text.getTextBlocks()) {
            for (Text.Line line : block.getLines()) {
                String diamondId = mModel.extractDiamondId(line.getText().trim());
                if(!TextUtils.isEmpty(diamondId)){
                    lines.add(line);
                }
            }
        }
        mView.onGetRecognizeTexts(lines);
    }

}
